package com.ruoyi.user.service.impl;

import cn.dev33.satoken.jwt.SaJwtUtil;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.enums.DeviceType;
import com.ruoyi.common.dtos.ResponseResult;
import com.ruoyi.common.enums.AppHttpCodeEnum;
import com.ruoyi.common.satoken.utils.LoginHelper;
import com.ruoyi.user.domain.ApUser;
import com.ruoyi.user.mapper.ApUserMapper;
import com.ruoyi.user.service.ApUserService;
import com.ruoyi.user.dtos.LoginDto;
import com.ruoyi.utils.common.AppJwtUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@RequiredArgsConstructor
@Service
public class ApUserServiceImpl implements ApUserService {

    private final ApUserMapper baseMapper;
    @Override
    public ResponseResult login(LoginDto dto) {

        //1.正常登录（手机号+密码登录）
        if (!StringUtils.isBlank(dto.getPhone()) && !StringUtils.isBlank(dto.getPassword())) {
            //1.1查询用户
            ApUser apUser = baseMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            //1.2 比对密码
            if(!BCrypt.checkpw(dto.getPassword(), apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.3 返回数据  jwt
            Map<String, Object> map = new HashMap<>();
            //map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("token", LoginHelper.login4News(apUser.getId(), DeviceType.APP));
            //清除敏感数据
            apUser.setPassword("");
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        } else {
            //2.游客  同样返回token  id = 0
            Map<String, Object> map = new HashMap<>();
            //map.put("token", AppJwtUtil.getToken(0l));
            map.put("token", LoginHelper.login4News(0, DeviceType.APP));
            return ResponseResult.okResult(map);
        }


    }


}
